import { setToken, getToken, removeToken } from '@/untils'
import { createSlice } from '@reduxjs/toolkit'
import { getTokenAPI, getUserInfoAPI } from '@/api/use'

const useStore = createSlice({
    name: 'user',
    initialState: {
        token: getToken() || '',
        userInfo: {}
    },
    reducers: {
        reducerToken(state, action) {
            state.token = action.payload
            setToken(action.payload)
        },
        setUserInfo(state, action) {
            state.userInfo = action.payload
        },
        logout(state) {
            state.token = ''
            state.userInfo = {}
            removeToken()
        }
    }
})

const { reducerToken, setUserInfo, logout } = useStore.actions

const fetchToken = (params) => {
    return async (dispatch) => {
        const res = await getTokenAPI(params)
        dispatch(reducerToken(res.data.token))
    }
}

const getUserInfo = () => {
    return async (dispatch) => {
        const res = await getUserInfoAPI()
        dispatch(setUserInfo(res.data))
    }
}

export { fetchToken, getUserInfo, logout }

const useReducer = useStore.reducer

export default useReducer